# -*- coding: utf-8 -*

from google.appengine.ext import db
import geo.geomodel
import config

class Stop(geo.geomodel.GeoModel):
    name = db.StringProperty()


class Line(db.Model):
    name = db.StringProperty()
    type = db.CategoryProperty()


class LineStop(db.Model):
    line = db.ReferenceProperty(reference_class=Line)
    stop = db.ReferenceProperty(reference_class=Stop,
                                collection_name='from_set')
    stopNext = db.ReferenceProperty(reference_class=Stop,
                                    collection_name='to_set')

class HotSpotCategory(db.Model):
    name = db.StringProperty()


class HotSpot(geo.geomodel.GeoModel):
    name = db.StringProperty()
    desc = db.StringProperty()
    spendMoney = db.IntegerProperty()
    spendTime = db.IntegerProperty()
    openTime = db.ByteStringProperty()
    category = db.ReferenceProperty(reference_class=HotSpotCategory,
                                    collection_name='spot_set')

    def __eq__(self, rhs):
        return self.key() == rhs.key()

    def __hash__(self):
        return hash(self.key())

    @staticmethod
    def get_in_bound(ne_lat, ne_lon, sw_lat, sw_lon):
        if ne_lon > sw_lon:
            ne_geo_pt = db.GeoPt(ne_lat, ne_lon)
            sw_geo_pt = db.GeoPt(sw_lat, sw_lon)
            return HotSpot.all() \
                   .filter('location >=', sw_geo_pt) \
                   .filter('location <=', ne_geo_pt) \
                   .fetch(config.MAX_SPOT_QUERY_NUM)

        else:
            # international date line is in the middle

            left_sw_geo_pt = db.GeoPt(sw_lat, sw_lon)
            left_ne_geo_pt = db.GeoPt(ne_lat, 180.0)
            left_rows = HotSpot.all() \
                        .filter('location >=', left_sw_geo_pt) \
                        .filter('location <=', left_ne_geo_pt) \
                        .fetch(config.MAX_SPOT_QUERY_NUM)

            right_sw_geo_pt = db.GeoPt(sw_lat, -180.0)
            right_ne_geo_pt = db.GeoPt(ne_lat, ne_lon)
            right_rows = HotSpot.all() \
                         .filter('location >=', right_sw_geo_pt) \
                         .filter('location <=', right_ne_geo_pt) \
                         .fetch(config.MAX_SPOT_QUERY_NUM)

            rows = set(left_rows)
            rows.union(right_rows)
            return rows


class MrtPrice(db.Model):
    stopStart = db.ReferenceProperty(reference_class=Stop,
                                     collection_name='start_set')

    stopEnd = db.ReferenceProperty(reference_class=Stop,
                                   collection_name='end_set')

    price = db.IntegerProperty()
